package com.example.work;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONUtil;
import com.example.Phone.JsonRootBean;

import com.example.Weahter.Data4;
import com.example.Weahter.FifteenDayWeather;
import com.example.Weahter.WeatherData;
import com.example.client.Client;
import com.example.movie.Data;
import com.example.movie.Data1;
import com.example.movie.MovieData;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Controller {
    static Connection con; // 声明Connection对象
    static Statement stmt;
    static ResultSet res;
    String selectSql;
    String addSql;
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static String user;
    static String password;
    static String DBName;
    static String url;
    @FXML
    private ChoiceBox searchMovieType;
    @FXML
    private TextField searchMovieText;
    @FXML
    private ListView<Object> listView;
    private ImageView imgV;
    private Label movieName;
    private Label movieType;
    private Label movieDirector;
    private Label movieActors;
    private Label movieReleaseDateStr;
    @FXML
    private TextField searchPhoneText;
    @FXML
    private TextField searchWeatherText;

    @FXML
    protected void onNewMovieClick() throws SQLException {
        listView.getItems().clear();
        ObservableList<Object> contentLabelList = FXCollections.observableArrayList();
        //ObservableList<Label> filed = FXCollections.observableArrayList();
        String data = Client.GET("https://qqlykm.cn/api/jijiangshangying/get?key=XN9rMU17KyP4s7wg7BEPU7CSqk");
        MovieData movieData = JSONUtil.toBean(data, MovieData.class);
        ArrayList<Data> list = new ArrayList<Data>(movieData.getData());
        listView.setPrefWidth(450);

        user = "root";//数据库登录名
        password = "1234";//密码
        DBName = "demo";//数据库名称
        url = "jdbc:mysql://localhost:3306/" + DBName + "?useSSL=false&charset=utf8";
        try { // 通过访问数据库的URL获取数据库连接对象
            //Class.forName(JDBC_DRIVER);
            con = DriverManager.getConnection(url, user, password);//获取数据库连接句柄
            stmt = con.createStatement();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        }
        for (Data dataItem : list) {
            Image image = new Image(dataItem.getPicUrl(), 150, 210, false, false);
            imgV = new ImageView(image);
            movieName = new Label(dataItem.getTitle());
            String name = movieName.getText();
            selectSql = "select * from moviedb where title='" + dataItem.getTitle() + "'";
            res = stmt.executeQuery(selectSql);
            //没有数据则添加进数据库
            if (!res.next()) {
                addSql = "insert into moviedb (title , type , director , actors , date) values ('" + dataItem.getTitle() + "','" + dataItem.getType() + "','" + dataItem.getDirector() + "','" + dataItem.getActors() + "','" + dataItem.getReleaseDateStr() + "')";
                stmt.executeUpdate(addSql);
            }

            movieType = new Label(dataItem.getType());
            String type = movieType.getText();

            movieDirector = new Label(dataItem.getDirector());
            String director = movieDirector.getText();

            movieActors = new Label(dataItem.getActors());
            String actors = movieActors.getText();

            movieReleaseDateStr = new Label(dataItem.getReleaseDateStr());
            String date = movieReleaseDateStr.getText();

            contentLabelList.add(imgV);
            contentLabelList.add("电影：" + name);
            contentLabelList.add("类型：" + type);
            contentLabelList.add("导演：" + director);
            contentLabelList.add("演员：" + actors);
            contentLabelList.add("放映时间：" + date);
        }
        listView.setItems(contentLabelList);
        con.close();
    }

    @FXML
    protected void onSearchMovieClick() throws SQLException {
        Stage dateView = new Stage();
        TableView<Data1> table = new TableView();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        TableColumn title = new TableColumn<Data1, String>("电影");
        TableColumn type = new TableColumn<Data1, String>("类型");
        TableColumn director = new TableColumn<Data1, String>("导演");
        TableColumn actors = new TableColumn<Data1, String>("演员");
        TableColumn date = new TableColumn<Data1, String>("时间");
        title.setCellValueFactory(new PropertyValueFactory<>("title"));
        type.setCellValueFactory(new PropertyValueFactory<>("type"));
        director.setCellValueFactory(new PropertyValueFactory<>("director"));
        actors.setCellValueFactory(new PropertyValueFactory<>("actors"));
        date.setCellValueFactory(new PropertyValueFactory<>("releaseDateStr"));

        dataMovie(table, title, type, director, actors, date);
        table.getColumns().addAll(title, type, director, actors, date);
        Scene scene = new Scene(table, 500, 400);
        dateView.setTitle("电影库");
        dateView.setScene(scene);
        dateView.show();
        con.close();

    }

    public void dataMovie(TableView table, TableColumn title, TableColumn type, TableColumn director, TableColumn actors, TableColumn date) throws SQLException {
        ObservableList<Data1> contentLabelList = FXCollections.observableArrayList();
        user = "root";//数据库登录名
        password = "1234";//密码
        DBName = "demo";//数据库名称
        url = "jdbc:mysql://localhost:3306/" + DBName + "?useSSL=false&charset=utf8";
        try { // 通过访问数据库的URL获取数据库连接对象
            // Class.forName(JDBC_DRIVER);
            con = DriverManager.getConnection(url, user, password);//获取数据库连接句柄
            stmt = con.createStatement();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        }
        if ("名称".equals(searchMovieType.getValue())) {
            selectSql = "select * from moviedb where locate(\"" + searchMovieText.getText() + "\" , title)";
        } else if ("类型".equals(searchMovieType.getValue())) {
            selectSql = "select * from moviedb where locate(\"" + searchMovieText.getText() + "\" , type)";
        } else if (searchMovieText.getText().equals("")) {
            selectSql = "select * from moviedb";
        }
//        selectSql = "select * from moviedb";
        ResultSet res = stmt.executeQuery(selectSql);
        while (res.next()) {
            contentLabelList.add(new Data1(res.getString("title"), res.getString("type"), res.getString("director"), res.getString("actors"), res.getString("date")));
            table.setItems(contentLabelList);
        }
    }

    @FXML
    protected void onSearchPhoneClick() throws SQLException {
        listView.getItems().clear();
        String regex = "^[1][3,4,5,7,8][0-9]{9}$";//电话号码正则表达式
        Pattern pattern = Pattern.compile(regex);// 编译正则表达式
        Matcher matcher = pattern.matcher((searchPhoneText.getText()));// 创建给定输入模式的匹配器
        boolean bool = matcher.matches();

        ObservableList<Object> contentLabelList = FXCollections.observableArrayList();


        if (bool) {
            user = "root";//数据库登录名
            password = "1234";//密码
            DBName = "demo";//数据库名称
            url = "jdbc:mysql://localhost:3306/" + DBName + "?useSSL=false&charset=utf8";
            try { // 通过访问数据库的URL获取数据库连接对象
                //Class.forName(JDBC_DRIVER);
                con = DriverManager.getConnection(url, user, password);//获取数据库连接句柄
                stmt = con.createStatement();
            } catch (SQLException se) {
                // 处理 JDBC 错误
                se.printStackTrace();
            } catch (Exception e) {
                // 处理 Class.forName 错误
                e.printStackTrace();
            }
            selectSql = "select * from phonedb where locate(\"" + searchPhoneText.getText() + "\" , phone)";
            ResultSet res = stmt.executeQuery(selectSql);

            if (!res.next()) {
                String data = Client.GET("https://qqlykm.cn/api/QCellCore/get?key=XN9rMU17KyP4s7wg7BEPU7CSqk&phone=" + searchPhoneText.getText());
                JsonRootBean jsonRootBean = JSONUtil.toBean(data, JsonRootBean.class);
                String province = jsonRootBean.getData().getProvince();
                String city = jsonRootBean.getData().getCity();
                String facilitator = jsonRootBean.getData().getFacilitator();
                String postcode = jsonRootBean.getData().getPostcode();
                addSql = "insert into phonedb (phone, province, city, facilitator, postcode) values ('" + searchPhoneText.getText() + "', '" + province + "', '" + city + "', '" + facilitator + "', '" + postcode + "')";
                stmt.executeUpdate(addSql);
                ResultSet res1 = stmt.executeQuery(selectSql);
                while (res1.next()) {
                    contentLabelList.add("电话号码：" + res1.getString("phone"));
                    contentLabelList.add("归属地省份：" + res1.getString("province"));
                    contentLabelList.add("归属地城市：" + res1.getString("city"));
                    contentLabelList.add("运营商：" + res1.getString("facilitator"));
                    contentLabelList.add("邮政编码：" + res1.getString("postcode"));
                }
            } else {
                contentLabelList.add("电话号码：" + res.getString("phone"));
                contentLabelList.add("归属地省份：" + res.getString("province"));
                contentLabelList.add("归属地城市：" + res.getString("city"));
                contentLabelList.add("运营商：" + res.getString("facilitator"));
                contentLabelList.add("邮政编码：" + res.getString("postcode"));

            }

            listView.setItems(contentLabelList);
            con.close();
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.titleProperty().set("错误提示");
            alert.headerTextProperty().set("输入的电话号码不正确！请重新输入");
            alert.showAndWait();
        }
    }

    @FXML
    protected void onSearchWeatherClick() throws SQLException {
        if(searchWeatherText.getText().equals("")){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.titleProperty().set("错误提示");
            alert.headerTextProperty().set("搜索框为空！请输入");
            alert.showAndWait();
        }
        String PinYin = PinyinUtil.getPinyin(searchWeatherText.getText());
        PinYin = PinYin.replaceAll(" ","");
        user = "root";//数据库登录名
        password = "1234";//密码
        DBName = "WeatherDB";//数据库名称
        url = "jdbc:mysql://localhost:3306/" + DBName + "?useSSL=false&charset=utf8";
        try { // 通过访问数据库的URL获取数据库连接对象
            //Class.forName(JDBC_DRIVER);
            con = DriverManager.getConnection(url, user, password);//获取数据库连接句柄
            stmt = con.createStatement();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        }
        String showSql = "show tables like '"+PinYin+"'";
        ResultSet res = stmt.executeQuery(showSql);
        if(!res.next()){
            String createSql = "create table "+PinYin+" (date varchar(255), timeText varchar(255), weather varchar(255), temp varchar(255), windDirection varchar(255), windLevel varchar(255), aqiLevel varchar(255)) default charset=utf8";
            stmt.executeUpdate(createSql);
            String client = Client.GET("https://qqlykm.cn/api/weatherv2/get?key=XN9rMU17KyP4s7wg7BEPU7CSqk&city="+PinYin);
            client=client.replace("15dayweather","fifteenDayWeather");
            client=client.replace("40dayweatherTrend","fortyDayWeather");
            WeatherData data3 = JSONUtil.toBean(client, WeatherData.class);
            List<FifteenDayWeather> list = new ArrayList<>(data3.getData().getFifteenDayWeather());

            for(FifteenDayWeather dataItem : list){
                String date_ = dataItem.getDate();
                String timeText_ = dataItem.getTimeText();
                String weather_ = dataItem.getWholeWeather();
                String temp_ = dataItem.getWholeTemp();
                String windDirection_ = dataItem.getDayWindDirection();
                String windLevel_ = dataItem.getDayWindLevel();
                String aqiLevel_ = dataItem.getAqiLevelInfo();
                addSql = "insert into "+PinYin+" (date , timeText , weather , temp , windDirection, windLevel, aqiLevel) values ('" + date_ + "','" + timeText_ + "','" + weather_ + "','" + temp_ + "','" + windDirection_ + "','"+windLevel_+"','"+aqiLevel_+"')";
                stmt.executeUpdate(addSql);
            }
        }
        Stage dateView = new Stage();
        TableView<Data4> table = new TableView();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        TableColumn date = new TableColumn<Data4, String>("日期");
        TableColumn timeText = new TableColumn<Data4, String>("星期");
        TableColumn weather = new TableColumn<Data4, String>("天气");
        TableColumn temp = new TableColumn<Data4, String>("温度");
        TableColumn windDirection = new TableColumn<Data4, String>("风向");
        TableColumn windLevel = new TableColumn<Data4, String>("风级");
        TableColumn aqiLevel = new TableColumn<Data4, String>("空气质量");
        date.setCellValueFactory(new PropertyValueFactory<>("date"));
        timeText.setCellValueFactory(new PropertyValueFactory<>("timeText"));
        weather.setCellValueFactory(new PropertyValueFactory<>("weather"));
        temp.setCellValueFactory(new PropertyValueFactory<>("temp"));
        windDirection.setCellValueFactory(new PropertyValueFactory<>("windDirection"));
        windLevel.setCellValueFactory(new PropertyValueFactory<>("windLevel"));
        aqiLevel.setCellValueFactory(new PropertyValueFactory<>("aqiLevel"));

        selectSql = "select * from "+PinYin;
        ResultSet res2 = stmt.executeQuery(selectSql);
        ObservableList<Data4> contentLabelList = FXCollections.observableArrayList();
        while (res2.next()){
            String date_ = res2.getString("date");
            String timeText_ = res2.getString("timeText");
            String weather_ = res2.getString("weather");
            String temp_ = res2.getString("temp");
            String windDirection_ = res2.getString("windDirection");
            String windLevel_ = res2.getString("windLevel");
            String aqiLevel_ = res2.getString("aqiLevel");
            contentLabelList.add(new Data4(date_, timeText_, weather_, temp_, windDirection_, windLevel_, aqiLevel_));
            table.setItems(contentLabelList);
        }

        table.getColumns().addAll(date, timeText, weather, temp, windDirection, windLevel, aqiLevel);
        Scene scene = new Scene(table, 600, 400);
        dateView.setTitle(searchWeatherText.getText()+"近15天的天气");
        dateView.setScene(scene);
        dateView.show();
    }

}


